package com.example.yyh.recorddemo.manager;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.yyh.recorddemo.application.App;
import com.example.yyh.recorddemo.bean.SoundBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yaoyh on 2018/12/1.
 */

public class RecordDbManager {

    /*-------------------------------------创建单例对象------------------------------------------*/

    private static RecordDbManager INSTANCE;

    private RecordDbManager() {
        if (App.getCurrentApp() == null) {
            Log.e("debug", "App.getCurrentApp()== null");
            return;
        }
        mDbHelper = new DBHelper(App.getCurrentApp(), DB_NAME, null, VERSION_CODE);//实例化DbHelper
        mDb = mDbHelper.getWritableDatabase();//通过DbHelper获取数据库操作对象
        if (INSTANCE != null) {
            throw new RuntimeException("单例漏洞");//防止单例反射
        }
    }

    public static RecordDbManager getInstance() {
        if (INSTANCE == null) {
            synchronized (RecordDbManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new RecordDbManager();
                }
            }
        }
        return INSTANCE;
    }



    /*-------------------------------------数据库操作------------------------------------------*/


    //声明数据库对象
    private SQLiteDatabase mDb;
    //
    private DBHelper mDbHelper;
    //数据库名
    private final String DB_NAME = "record.db";
    //表名
    private final String TABLE_NAME = "sound_info";
    //数据库版本
    private final int VERSION_CODE = 1;

    /**
     * 创建DBHelper类
     */
    private class DBHelper extends SQLiteOpenHelper {

        private String SQL_CAREATE_DB = "CREATE TABLE IF NOT EXISTS "//
                + TABLE_NAME
                + " ("
                + //
                SoundBean.Column.AUTO_ID
                + " INTEGER PRIMARY KEY AUTOINCREMENT, " + //
                SoundBean.Column.ID + " TEXT UNIQUE, " + //
                SoundBean.Column.NAME + " TEXT, " + //
                SoundBean.Column.TIME + " TEXT, " + //
                SoundBean.Column.FILESIZE + " TEXT, " + //
                SoundBean.Column.FILEPATH + " TEXT" + //
                ")";//

        public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
                        int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(SQL_CAREATE_DB);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        }

    }


    /**
     * 音频总数
     *
     * @return
     */
    public int getTotalCount() {
        Cursor cursor = mDb.rawQuery("SELECT COUNT(*) FROM " + TABLE_NAME, null);

        int number = 0;
        cursor.moveToFirst();
        if (!cursor.isAfterLast()) {
            number = cursor.getInt(0);
        }
        cursor.close();

        return number;
    }

    /**
     * 获取所有音频数据
     *
     * @return
     */
    public List<SoundBean> getAllSoundInfo() {
        List<SoundBean> sounds = new ArrayList<SoundBean>();

        Cursor cursor = mDb
                .query(TABLE_NAME, null, null, null, null, null, null);

        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            sounds.add(new SoundBean(cursor));
        }

        cursor.close();
        return sounds;
    }

    /**
     * 保存或更新
     *
     * @param soundBean
     */
    public boolean saveOrUpdate(SoundBean soundBean) {
        boolean result = false;
        Cursor cursor = mDb.query(TABLE_NAME, null, SoundBean.Column.ID
                + " = ?", new String[]{soundBean.getId()}, null, null, null);
        int count = cursor.getCount();
        cursor.close();
        if (count == 0) {
            result = save(soundBean);
        } else {
            result = update(soundBean);
        }
        return result;
    }

    /**
     * 保存
     *
     * @param soundBean
     */
    public boolean save(SoundBean soundBean) {
        long count = mDb.insert(TABLE_NAME, null, soundBean.getContentValus());
        return (count != 0) ? true : false;
    }

    /**
     * 更新
     *
     * @param
     */
    public boolean update(SoundBean soundBean) {
        long count = mDb.update(TABLE_NAME, soundBean.getContentValus(), SoundBean.Column.ID
                + " = ?", new String[]{soundBean.getId()});
        return (count != 0) ? true : false;
    }

    /**
     * 删除
     */

    /**
     * 根据id删除用户信息
     *
     * @param id
     */
    public boolean deleteById(String id) {
        int result = mDb.delete(TABLE_NAME, SoundBean.Column.ID + " = ?",
                new String[]{id});
        return result != 0;
    }
}
